package cn.edu.zafu.bigdata.psy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class AppendAndReadfile {

    // 将用户输入的文本追加到指定文件中
    public static void appendToFile(String fileName, String content) {
        try {
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
            System.out.println("文本已成功追加到文件：" + fileName);
        } catch (IOException e) {
            System.out.println("追加文本到文件时出错：" + e.getMessage());
        }
    }

    // 读取文件内容并打印
    public static void readFile(String fileName) {
        try {
            File file = new File(fileName);
            Scanner scanner = new Scanner(file);

            System.out.println("文件内容如下：");
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("读取文件时出错：找不到文件 " + fileName + "，原因：" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入你的学号：");
        String studentId = scanner.nextLine();

        String fileLocation = "files/" + studentId + ".txt";

        System.out.print("请输入要追加的文本内容：");
        String inputText = scanner.nextLine();

        // 追加文本到文件
        appendToFile(fileLocation, inputText);

        // 读取文件内容
        readFile(fileLocation);

        scanner.close();
    }
}